package com.cloudeasy.user.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloudeasy.api.vo.PageResult;
import com.cloudeasy.api.vo.user.RoleVO;
import com.cloudeasy.user.po.Role;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色工具类
 */
public class RoleUtil {
    /**
     * 构建
     *
     * @param ids    角色Id列表
     * @param names  角色名称列表
     * @param enable 是否启用
     * @return {@link QueryWrapper<Role>}
     */
    public static QueryWrapper<Role> compose(List<String> ids, List<String> names,
                                             Boolean enable) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            queryWrapper.in("id", ids);
        }
        if (names != null && names.size() > 0) {
            queryWrapper.and(roleQueryWrapper -> {
                names.forEach(name -> roleQueryWrapper.or(roleTempQueryWrapper ->
                        roleTempQueryWrapper.like("name", name)));
                return roleQueryWrapper;
            });
        }
        if (enable != null) {
            queryWrapper.eq("enable", enable);
        }
        return queryWrapper;
    }

    /**
     * 转换VO对象
     *
     * @param role {@link Role}
     * @return {@link RoleVO}
     */
    public static RoleVO convert(Role role) {
        RoleVO roleVO = new RoleVO();
        BeanUtils.copyProperties(role, roleVO);
        return roleVO;
    }

    /**
     * 转换VO对象
     *
     * @param roles {@link List<Role>}
     * @return {@link List<RoleVO>}
     */
    public static List<RoleVO> convert(List<Role> roles) {
        return roles.stream().map(RoleUtil::convert).collect(Collectors.toList());
    }

    /**
     * 转换VO对象
     *
     * @param roleIPage {@link IPage<Role>}
     * @return {@link PageResult<RoleVO>}
     */
    public static PageResult<RoleVO> convert(IPage<Role> roleIPage) {
        PageResult<RoleVO> pageResult = new PageResult<>();
        pageResult.setTotal(roleIPage.getTotal())
                .setPages(roleIPage.getPages())
                .setRecords(roleIPage.convert(RoleUtil::convert).getRecords());
        return pageResult;
    }
}
